import logging
import cgi
import re
import wsgiref.handlers

import cssutils
from BeautifulSoup import BeautifulSoup

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.api import urlfetch

class MainPage(webapp.RequestHandler):
  def get(self):
    self.response.out.write("""
      <html>
		<title>The 2.0dium Validator</title>
        <body>
		  <h1 style="color:#f90">Enter a URL to validate</h1>
          <form action="/results" method="post">
            <div><input name="url" size="50"><input type="submit" value="Validate"></div>
            <h2>Welcome to the Web 2.0dium Validator. This was inspired by <a href="http://www.webstock.org.nz/programme/presentations.php#conway">Damian Conway's talk</a> at Webstock 08</h2>
            <p>Created by <a href="http://maetl.coretxt.net.nz">Mark Rickerby</a>. Thanks to Terrence Wood <a href="http://twitter.com/terrencewood/statuses/742367892">for the idea</a>, and Sean Harvey, and Geoff Munn for suggestions.</p>
          </form>
        </body>
      </html>""")


class Validator(webapp.RequestHandler):
  def post(self):
    self.response.out.write('<html><body><h1 style="color:#f90">Web 2.0dium Validator Results:</h1><ul>')
    
    score = 0

    url = cgi.escape(self.request.get('url'))
    
    w3v = 'http://validator.w3.org/check?uri=' + url
    w3_result = urlfetch.fetch(w3v)
    if w3_result.status_code == 200:
      valid = BeautifulSoup(w3_result.content)
      is_valid = valid.find('h2', {'class':'valid'})  
      if is_valid:
        self.response.out.write("<li>Valid HTML -2</li>")
        score -= 2
      else:
        self.response.out.write("<li>Invalid HTML +2</li>")
        score += 2
    
    result = urlfetch.fetch(url)
    if result.status_code == 200:
      
      doc = BeautifulSoup(result.content)
      
      css = doc.find('link', {'rel':'stylesheet'})
      if css:
	    self.response.out.write("<li>Uses external stylesheet -1</li>")
	    score -= 1

      from_word = doc.find('meta', {'name':'Generator', 'content': re.compile('Microsoft Word')})
      if from_word:
        self.response.out.write('<li>Generated by MS Word! +3</li>')
        score += 3
	
      h1 = doc.find('h1')
      if not h1:
        self.response.out.write("<li>No H1 tag +1</li>")
        score += 1

      frames = doc.find('frameset')
      if frames:
        self.response.out.write("<li>Uses frames +5</li>")
        score += 5

      links = doc.find('a')
      if not links:
        self.response.out.write('<li>No outgoing links - dead end page +5')
        score += 5
	  
      font = doc.find('font')
      if font:
        self.response.out.write('<li>Font tags used in body text +3')
        score += 3

      blink = doc.find(['blink', 'marquee'])
      if blink:
        self.response.out.write("<li>How could we fail to appreciate the blink/marquee tags? +3</li>")
        score += 3

      bgsound = doc.find('bgsound')
      if bgsound:
        self.response.out.write("<li>Use of bgsound is genius +8</li>")
        score += 8

    self.response.out.write('</ul>')
    if score < 0:
      details = 'Not good. Looks like your website might actually be usable'
    else:
      details = 'Looking good. Keep confusing those Morlocks'
    self.response.out.write('<h2 style="color:red">Your score is ' + str(score) + '! ' + details + '</h2>')
    self.response.out.write('<p><a href="/">Start again</a></body></html>')

def main():
  logging.getLogger().setLevel(logging.DEBUG)
  application = webapp.WSGIApplication(
                                       [('/', MainPage),
                                        ('/results', Validator)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()